package com.nxy.cpfsfe;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adtec.starring.exception.BaseException;
import com.adtec.starring.global.SysDef;
import com.adtec.starring.respool.SystemParameter;
import com.adtec.starring.respool.spring.LoadSpringFile;
import com.adtec.starring.util.SpringUtil;
import com.adtec.starring.util.StringTool;
import com.nxy.cpfsfe.enumtype.RespCd;
import com.nxy.cpfsfe.util.Encry;

public class MybatisInit {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MybatisInit.class);
	
	private static final String MYBATIS_CONFIG_FILENAME = "spring-mybatis-config.xml";
	
	public static void init(){
		LOGGER.info("Start Init Mybatis.....................");
		loadSpringMybatisXML(MYBATIS_CONFIG_FILENAME);
		LOGGER.info("End Init Mybatis.....................");
	}
	
	public static void loadSpringMybatisXML(String fileName){
		String fileFullName = SysDef.WORK_DIR + SystemParameter.SRC_PATH + SysDef.FILE_SP + fileName;
		LOGGER.info("加载Mybatis配置文件\n Mybatis配置文件路径:{}",fileFullName);
		
		File file = new File(fileFullName);
		String fileFullStr = "";
		InputStream fis = null;
		
		if(file.exists()){
			
			try {
				fis = new FileInputStream(file);
				int len = 0;
				byte[] buf = new byte[8192];
				while ((len = fis.read(buf)) != -1) {
					fileFullStr = new String(buf, 0, len);
				}

			} catch (Exception e1) {
				throw new BaseException(RespCd.NCPS1005, "加载Mybatis配置文件失败，读取配置文件时出现错误！");
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					LOGGER.info("加载Mybatis配置文件时，输入流关闭异常",e);
				}
			}
			
			if (fileFullStr.equals("")) {
				throw new BaseException(RespCd.NCPS1005, "加载Mybatis配置文件失败，该文件内容为空！");
			}
			

			
			try { 
    			LoadSpringFile loadSpring = (LoadSpringFile) SpringUtil.getBean("loadSpring");
    			loadSpring.loadSpringFileString(fileFullStr);
    			SpringUtil.getBean("mybatisSqlSessionFactory");
    			LOGGER.info("Init Mybatis Successful");
			} catch (Exception e) {
				LOGGER.info("加载Mybatis配置文件失败",e);
			}
		}else{
			throw new BaseException(RespCd.NCPS1005, "加载Mybatis配置文件失败，该文件不存在！");
		}
	}
	
}